import styles from './index.module.scss';
import { NavBar, TextArea, Toast } from 'antd-mobile';
import { useState } from 'react';
import { useDispatch } from 'react-redux';
import { useAppSelector } from '@/store';
import { getCommentsByIdAction } from '@/store/action/detail';
import { getReplyCommentsByIdAction, submitCommentAction } from '@/store/action/comment';
type Props = {
  name?: string;
  onBack: () => void;
};

export default function CommentInput({ name, onBack }: Props) {
  const [value, setValue] = useState('');
  const { detail } = useAppSelector((state) => state.article);
  const { originComment } = useAppSelector((state) => state.comment);
  const dispatch = useDispatch();
  const handleSubmit = async () => {
    if (originComment.com_id) {
      await dispatch(submitCommentAction(originComment.com_id, value, detail.art_id));

      dispatch(getReplyCommentsByIdAction(originComment.com_id));
      Toast.show({ content: '发表成功' });
      onBack();
      return;
    }
    await dispatch(submitCommentAction(detail.art_id, value));
    dispatch(getCommentsByIdAction({ type: 'a', source: detail.art_id }));
    Toast.show({ content: '发表成功' });
    onBack();
  };
  return (
    <div className={styles.root}>
      <NavBar
        right={
          <span onClick={handleSubmit} className="publish">
            发表
          </span>
        }
        onBack={onBack}
      >
        {name ? '回复评论' : '评论文章'}
      </NavBar>
      <div className="input-area">
        {name && <div className="at">@{name}:</div>}

        <TextArea
          placeholder="说点什么~"
          rows={10}
          value={value}
          onChange={(strValue) => setValue(strValue)}
        />
      </div>
    </div>
  );
}
